package com.adream.scalpel.security.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;

public class LoginBox extends Composite {

    private Button signInButton;
    private TextBox userNameTextBox;
    private PasswordTextBox passwordTextBox;
    private Label passwordLabel;
    private Label userNameLabel;
    private FlexTable flexTable;

    public LoginBox() {

        flexTable = new FlexTable();
        initWidget(flexTable);

        userNameLabel = new Label("User Name :");
        flexTable.setWidget(0, 0, userNameLabel);
        flexTable.getCellFormatter().setWidth(0, 0, "40%");
        flexTable.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_RIGHT);

        passwordLabel = new Label("Password :");
        flexTable.setWidget(1, 0, passwordLabel);
        flexTable.getCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_RIGHT);

        passwordTextBox = new PasswordTextBox();
        flexTable.setWidget(1, 1, passwordTextBox);
        passwordTextBox.setTabIndex(2);
        passwordTextBox.addKeyUpHandler(new KeyUpHandler() {
            public void onKeyUp(KeyUpEvent event) {
                onKeyUpPasswordTextBox(event);
            }
        });
        passwordTextBox.setWidth("100%");
        passwordTextBox.setMaxLength(20);

        userNameTextBox = new TextBox();
        flexTable.setWidget(0, 1, userNameTextBox);
        userNameTextBox.setTabIndex(1);
        userNameTextBox.addKeyUpHandler(new KeyUpHandler() {
            public void onKeyUp(KeyUpEvent event) {
                onKeyUpUserNameTextBox(event);
            }
        });
        userNameTextBox.setWidth("100%");
        flexTable.getCellFormatter().setWidth(0, 1, "60%");
        userNameTextBox.setMaxLength(20);

        signInButton = new Button();
        flexTable.setWidget(2, 0, signInButton);
        signInButton.setTabIndex(3);
        signInButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                onClickSignInButton(event);
            }
        });
        flexTable.getCellFormatter().setHorizontalAlignment(2, 0, HasHorizontalAlignment.ALIGN_CENTER);
        flexTable.getFlexCellFormatter().setColSpan(2, 0, 2);
        signInButton.setText("Sign In");
        userNameTextBox.setFocus(true);
    }

    private void autheticateUser() {
        setFormLatch(true);
        // LoginVO loginVO = new LoginVO();
        // loginVO.setLoginName(userNameTextBox.getText());
        // loginVO.setPassword(passwordTextBox.getText());
        //
        // try {
        // new LoginValidator().validate(loginVO);
        // } catch (InvalidDataException invalidDataException) {
        // System.out.println("Invalid Username or Password");
        // setFormLatch(false);
        // return;
        // }

        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, GWT.getHostPageBaseURL()
                + "Scalpel/j_spring_security_check");
        String requestString = "j_username=" + URL.encodeComponent(userNameTextBox.getText());
        requestString += "&j_password=" + URL.encodeComponent(passwordTextBox.getText());
        requestString += "&ajax=" + URL.encodeComponent("true");

        requestBuilder.setRequestData(requestString);
        requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded");
        requestBuilder.setCallback(new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                Window.alert("Error:  " + exception.getMessage());
                setFormLatch(false);
            }

            public void onResponseReceived(Request request, Response response) {
                String responseText = response.getText();

                if (responseText.indexOf("error:") >= 0) {
                    Window.alert("Could not log on. Invalid user or incorrect password!");
                } else if (responseText.indexOf("url:") >= 0) {
                    String url = responseText.replaceFirst("url:", "");
                    String host = Location.getHost();
                    String protocol = Location.getProtocol();
                    Location.assign(protocol + "//" + host + url);
                } else {
                    Window.alert("Well the server seems to have gone crazy! Try again later.");
                }
                setFormLatch(false);
            }
        });
        try {
            requestBuilder.send();
        } catch (RequestException e) {
            e.printStackTrace();
        }
    }

    private void onClickSignInButton(final ClickEvent event) {
        autheticateUser();
    }

    private void onKeyUpPasswordTextBox(KeyUpEvent event) {
        if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
            autheticateUser();
        }
    }

    private void onKeyUpUserNameTextBox(KeyUpEvent event) {
        if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
            autheticateUser();
        }
    }

    private void setFormLatch(boolean formLocked) {
        userNameTextBox.setEnabled(!formLocked);
        passwordTextBox.setEnabled(!formLocked);
        signInButton.setEnabled(!formLocked);
    }
}
